package standalone

import (
	"github.com/DiracLee/dires-go/app/cmdline"
	"github.com/DiracLee/dires-go/app/config"
	"github.com/DiracLee/dires-go/app/connection"
	"github.com/DiracLee/dires-go/app/payload"
)

func handleAuth(conn connection.Connection, args cmdline.CmdLine) payload.Payload {
	if len(args) != 1 {
		return payload.NewErrPayload("ERR wrong number of arguments for 'auth' command")
	}
	// TODO: support multi user, for now: `auth password`
	if config.GetPassWord() == "" {
		return payload.NewErrPayload("ERR Client sent AUTH, but no password is set")
	}
	passwd := string(args[0])
	conn.SetPassword(passwd)
	if config.GetPassWord() != passwd {
		return payload.NewErrPayload("ERR invalid password")
	}
	return &payload.OkPayload{}
}

func isAuthenticated(conn connection.Connection) bool {
	if config.GetPassWord() == "" {
		return true
	}
	return conn.GetPassword() == config.GetPassWord()
}
